package com.gis3c.sys.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.gis3c.common.exception.DataException;
import com.gis3c.sys.entry.po.Token;
import com.gis3c.sys.entry.po.User;
import com.gis3c.sys.dao.UserDao;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
	@Resource(name="sqlSessionFactory_sys") private SqlSessionFactory sqlSessionFactory;

	@Override
	public User createUser(User user) {
		getSqlSession().insert("UserSql.createUser", user);
		return user;
	}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub

	}

	@Override
	public int deleteUser(String userId) {
		Map<String,Object> params = new HashMap<>();
		params.put("userId", userId);
		return getSqlSession().delete("UserSql.deleteUser", params);
	}
	
	@Override
	public int deleteUsers(String[] userIds){
		return getSqlSession().delete("UserSql.deleteUsers",Arrays.asList(userIds));
	}

	@Override
	public void changePassword(String userId, String newPassword,String newSalt){
		Map<String,Object> params = new HashMap<>();
		params.put("userid", userId);
		params.put("password", newPassword);
		params.put("salt", newSalt);
		getSqlSession().update("UserSql.changePassword",params);
	}

	@Override
	public User findOne(String userId) {
		// TODO Auto-generated method stub
		return getSqlSession().selectOne("UserSql.findOneUser",userId);
	}

	@Override
	public User findByUsername(String username) {
		// TODO Auto-generated method stub
		return getSqlSession().selectOne("UserSql.findByUsername",username);
	}
	
	@Override
	public int userCount(String username){
		return getSqlSession().selectOne("UserSql.userCount",username);
	}
	
	@Override
	public List<User> allUsers(){
		return getSqlSession().selectList("UserSql.allUsers");
	}

	@Override
	public List<User> allUsersByPage(int pagesize, int currentpage){
		Map<String,Object> params = new HashMap<>();
		params.put("pagesize",pagesize);
		params.put("offsetNum",(currentpage-1)*pagesize);

		return getSqlSession().selectList("UserSql.allUsersByPage",params);
	}

	@Override
	public int allUsersCount(){
		return getSqlSession().selectOne("UserSql.allUsersCount");
	}

	@Override
	public List<String> findPermissions(String username) {
		return null;
	}
	
	@Override
	public void correlationOrg(String userId, String orgId){
		Map<String,Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("orgId", orgId);
		getSqlSession().insert("UserSql.correlationOrg", params);
	}
	
	@Override
    public void uncorrelationOrg(String userId){
		getSqlSession().delete("UserSql.uncorrelationOrg",userId);
    }

	@Override
	public List<User> findUsersByOrgId(String orgId){
		return getSqlSession().selectList("UserSql.findUsersByOrgId",orgId);
	}

	@Override
	public Token findTokenByUserId(String userId) {
		return getSqlSession().selectOne("UserSql.findTokenByUserId",userId);
	}



	@Override
	public List<Map<String,Object>> getUserWithToken(String userId) {
		List<Map<String,Object>> result = null;
		Map<String,Object> model = null;
		Map<String,Object> params = new HashMap<>();
		params.put("userId", userId);
		List<Map<String,Object>> rawResult= getSqlSession().selectList("UserSql.getUserWithToken",params);
		if(rawResult != null && rawResult.size() > 0){
			result = new ArrayList<>();
			for(Map<String,Object> map : rawResult){
				model = new HashMap<>();
				model.put("userId", map.get("USERID"));
				model.put("userName", map.get("USERNAME"));
				model.put("locked", map.get("LOCKED").toString());
				model.put("secretKey", map.get("SECRET_KEY")==null?"":map.get("SECRET_KEY").toString());
				model.put("token", map.get("TOKEN")==null?"":map.get("TOKEN"));
				model.put("createTime", map.get("UPDATE_TIME")==null?"":map.get("UPDATE_TIME"));
				result.add(model);
			}
		}
		
		return result;
	}

	@Override
	public int updateToken(Token token) {
		return getSqlSession().update("UserSql.updateToken",token);
	}

	@Override
	public int createToken(Token token) {
		return getSqlSession().insert("UserSql.createToken", token);
	}

	@Override
	public boolean exitToken(String userId) {
		Map<String,Object> params = new HashMap<>();
		params.put("userId", userId);
		int row= getSqlSession().selectOne("UserSql.exitToken", params);
		return row>0?true:false;
	}

	@Override
	public int deleteToken(String userId) {
		Map<String,Object> params = new HashMap<>();
		params.put("userId", userId);
		return getSqlSession().delete("UserSql.deleteToken", params);
	}

	@Override
	public String getUserNameByToken(String token){
		Map<String,Object> params = new HashMap<>();
		params.put("token", token);
		return getSqlSession().selectOne("UserSql.getUserNameByToken",params);
	}

	@Override
	public String getTokenByUserName(String userName){
		Map<String,Object> params = new HashMap<>();
		params.put("userName", userName);
		return getSqlSession().selectOne("UserSql.getTokenByUserName",params);
	}

	@Override
	public void updateTokeTime(String tokenStr){
		Map<String,Object> params = new HashMap<>();
		params.put("token", tokenStr);
		params.put("updateTime", new Timestamp((new Date()).getTime()));

		getSqlSession().update("UserSql.updateTokeTime",params);
	}

	@Override
	public String findsecretByUserName(String userName){
		String secretKey = null;
		try{
			secretKey = getSqlSession().selectOne("UserSql.findsecretByUserName", userName);
		}catch(Exception e){
			throw new DataException("获取数据失败",e);
		}
		return secretKey;
	}


	@PostConstruct
	public void injectSessionFactory(){
		super.setSqlSessionFactory(sqlSessionFactory);
	}
}
